package cn.com.wangluotongxin.netty;

import cn.com.wangluotongxin.netty.handler.NettyChannelInfoHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component(value = "nettyServerInitializer")
@Slf4j
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private NettyChannelInfoHandler mainDeviceRequestHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        // http服务解码
        pipeline.addLast(new HttpServerCodec());

        pipeline.addLast(new ChunkedWriteHandler());

        pipeline.addLast(new HttpObjectAggregator(8192));

        pipeline.addLast(new WebSocketServerProtocolHandler("/chat/netty",
                "Sec-WebSocket-Protocol", true, 65536*10));

        // 心跳检查，超时自动离线
        pipeline.addLast(new IdleStateHandler(0, 0, 0, TimeUnit.SECONDS));

        // netty通用请求
        pipeline.addLast(mainDeviceRequestHandler);
    }
}
